<template>
  <div class="main-content">
    <div class="table-wrapper">
      <!-- 搜索框 -->
      <div
        style="
          margin-bottom: 16px;
          display: flex;
          gap: 12px;
          align-items: center;
        "
      >
        <el-input
          v-model="keyword"
          placeholder="请输入标题或作者昵称"
          clearable
          style="width: 300px"
          @keyup.enter.native="fetchArticleList"
        />
        <el-button type="primary" @click="fetchArticleList">搜索</el-button>
      </div>

      <!-- 审核文章表格 -->
      <el-table :data="articleList" style="width: 100%">
        <el-table-column prop="articleTitle" label="标题" width="200" />
        <el-table-column prop="authorId" label="作者ID" width="100" />
        <el-table-column prop="authorName" label="作者名称" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #header>
            <span
              ref="headerRef"
              @click="showDatePickerNearHeader"
              style="cursor: pointer"
              >创建时间 📅</span
            >
            <teleport to="body">
              <div
                v-if="showDatePicker"
                class="picker-popup"
                :style="{ top: pickerTop + 'px', left: pickerLeft + 'px' }"
              >
                <el-date-picker
                  ref="datePickerRef"
                  v-model="createTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  clearable
                  @change="onDateChange"
                  @clear="handleClearDate"
                  @blur="hideDatePicker"
                />
              </div>
            </teleport>
          </template>
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #header>
            <el-popover placement="bottom" trigger="click" width="fit-content">
              <template #reference>
                <span style="cursor: pointer">状态 📋</span>
              </template>

              <div
                style="
                  display: flex;
                  flex-direction: column;
                  gap: 8px;
                  align-items: center;
                "
              >
                <el-tag
                  :type="''"
                  effect="plain"
                  size="small"
                  @click="selectStatus(null)"
                  :class="{
                    'is-active': selectedStatus === null,
                    'status-hover': true,
                  }"
                  class="status-option"
                  >全部</el-tag
                >

                <el-tag
                  type="warning"
                  effect="plain"
                  size="small"
                  @click="selectStatus(0)"
                  :class="{
                    'is-active': selectedStatus === 0,
                    'status-hover': true,
                  }"
                  class="status-option"
                  >待审核</el-tag
                >

                <el-tag
                  type="success"
                  effect="plain"
                  size="small"
                  @click="selectStatus(1)"
                  :class="{
                    'is-active': selectedStatus === 1,
                    'status-hover': true,
                  }"
                  class="status-option"
                  >通过</el-tag
                >

                <el-tag
                  type="danger"
                  effect="plain"
                  size="small"
                  @click="selectStatus(2)"
                  :class="{
                    'is-active': selectedStatus === 2,
                    'status-hover': true,
                  }"
                  class="status-option"
                  >拒绝</el-tag
                >
              </div>
            </el-popover>
          </template>

          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ statusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                size="small"
                type="primary"
                plain
                @click="viewArticle(row)"
                >查看</el-button
              >

              <el-tooltip
                v-if="row.status == 1"
                content="该文章已审核"
                placement="top"
              >
                <el-button size="small" type="success" plain disabled
                  >通过</el-button
                >
              </el-tooltip>
              <el-button
                v-else
                size="small"
                type="success"
                plain
                @click="approve(row)"
              >
                通过
              </el-button>

              <el-button
                size="small"
                type="danger"
                plain
                :disabled="row.status == 2"
                @click="reject(row)"
              >
                拒绝
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[1, 5, 10]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="fetchArticleList"
          layout="total, sizes, prev, pager, next"
          background
        />
      </div>
    </div>
  </div>
  <ArticleDetailDialog v-model="dialogVisible" :article="selectedArticle" />
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import ArticleDetailDialog from '../../../components/ArticleDetailDialog.vue'
import { getArticleDetail } from '@/apis/article'
import { getCheckingArticles, reviewArticle } from '@/apis/check'
import { useAccountStore } from '@/stores/useAccountStore.js'
const accountStore = useAccountStore()

const keyword = ref('')
const articleList = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const createTime = ref('')
const showDatePicker = ref(false)
const headerRef = ref(null)
const pickerTop = ref(0)
const pickerLeft = ref(0)
const datePickerRef = ref(null)
const selectedStatus = ref(null) // null 代表全部

const fetchArticleList = async () => {
  const res = await getCheckingArticles({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    keyWord: keyword.value.trim(),
    createTime: formatDateForBackend(createTime.value),
    uid: accountStore.uid,
    status: selectedStatus.value,
  })
  if (res.code === '200') {
    articleList.value = res.data.list
    total.value = res.data.total
  }
}
const selectStatus = (status) => {
  selectedStatus.value = status
  pageNum.value = 1
  fetchArticleList()
}

const approve = async (row) => {
  try {
    await ElMessageBox.confirm('确定要通过该文章审核吗？', '确认', {
      type: 'warning',
    })
    const res = await reviewArticle({
      articleId: row.articleId,
      status: 1,
      reason: '',
    })
    if (res.code === '200') {
      ElMessage.success('审核通过')
      fetchArticleList()
    }
  } catch {}
}

const reject = async (row) => {
  if (row.status === 2) return
  try {
    const { value: reason } = await ElMessageBox.prompt(
      '请输入拒绝理由：',
      '拒绝文章',
      {
        inputPlaceholder: '请填写拒绝原因',
        inputValidator: (val) => (val ? true : '拒绝理由不能为空'),
      }
    )
    const res = await reviewArticle({
      articleId: row.articleId,
      status: 2,
      reason,
    })
    if (res.code === '200') {
      ElMessage.success('审核已拒绝')
      fetchArticleList()
    }
  } catch {}
}

const showDatePickerNearHeader = async () => {
  await nextTick()
  const rect = headerRef.value.getBoundingClientRect()
  pickerTop.value = rect.bottom + 4
  pickerLeft.value = rect.left
  showDatePicker.value = true
  await nextTick()
  datePickerRef.value?.focus()
}

const hideDatePicker = () => {
  setTimeout(() => (showDatePicker.value = false), 200)
}

const handleClearDate = () => {
  createTime.value = ''
  pageNum.value = 1
  fetchArticleList()
  hideDatePicker()
}

const onDateChange = () => {
  hideDatePicker()
  pageNum.value = 1
  fetchArticleList()
}

const formatDate = (val) => dayjs(val).format('YYYY-MM-DD')
const formatDateForBackend = (val) => (val ? `${val}T00:00:00` : null)
const handleSizeChange = (size) => {
  pageSize.value = size
  pageNum.value = 1
  fetchArticleList()
}

const statusText = (status) => {
  switch (status) {
    case 0:
      return '待审核'
    case 1:
      return '通过'
    case 2:
      return '拒绝'
    default:
      return '未知'
  }
}
const statusTagType = (status) => {
  switch (status) {
    case 0:
      return 'warning'
    case 1:
      return 'success'
    case 2:
      return 'danger'
    default:
      return ''
  }
}

const dialogVisible = ref(false)
const selectedArticle = ref({})

const viewArticle = async (row) => {
  const res = await getArticleDetail(row.articleId)
  if (res.code === '200') {
    selectedArticle.value = res.data
    dialogVisible.value = true
  }
}

onMounted(() => {
  fetchArticleList()
})
</script>

<style scoped>
.picker-popup {
  position: fixed;
  z-index: 9999;
}
.table-wrapper {
  width: 100%;
  margin: 0 auto;
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding-top: 12px;
}
.main-content {
  padding: 0;
  width: 100%;
}
.action-buttons {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}
.status-option {
  cursor: pointer;
}

.status-hover:hover {
  background-color: rgba(0, 0, 0, 0.1); /* 可以修改为你想要的高亮颜色 */
}
</style>
